<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
    <el-form-item label="选择门店2" prop="orderId">
      <el-select
          v-model="queryParams.shopId"
          class="!w-240px"
        >
          <el-option
            v-for="item in shopList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>  
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>

  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div style="display: flex;flex-direction: row;width: 100%;">
      <div>
    <!-- <el-row >
      <el-col :span="5" style="min-height:700px;min-width:310px"> -->
        <div class="cart-container" >
            <div class="title">
              <div class="logo">
                收银员:
              </div>
              <div class="member-info">
                <span class="name">{{userStore.getUser.nickname}}</span>
              </div>
            </div>
            <div class="carts">
              <div>
                <div class="tab">
                  <div class="cart-list"  v-if="cartList.length > 0">
                    <div class="cart-item" v-for="(cart,idx) in cartList" :key="idx">
                      <img class="image" :src="cart.image"/>
                      <div class="info">
                        <div class="name">{{cart.storeName}}</div>
                        <div class="spec">
                          <span class="item" >{{cart.sku}}</span>
                        </div>
                        <div class="num"><el-input-number class="input" @change="changeBuyNum(cart)" v-model="cart.cartNum" :min="1" :max="1000"/></div>
                      </div>
                      <div class="option">
                        <div class="remove" @click="removeFromCart(cart.id)"><Icon icon="ep:delete" class="mr-5px" /> </div>
                        <div class="total">￥{{cart.price}}</div>
                      </div>
                    </div>
                  </div>
                  <div class="empty" v-else>
                    <el-empty description="暂无结算商品" :image-size="40" />
                  </div>
                </div>
              </div>
            </div>
            <div class="footer">
              <div class="number">
                <div class="total-num">总件数：<b class="num">{{getCartGoodsNumber}}</b></div>
                <div class="total-price">总金额：<b class="num">￥{{getCartGoodsPrice}}</b></div>
              </div>
              <div class="options">
                <div style="width:300px;margin-top:10px">
                <el-button type="primary" round @click="hangOff()">取单</el-button>
                <el-button type="warning" round @click="hangUp()">挂单</el-button>
                <el-button type="danger" round @click="doSettlement()">提交结算</el-button>
                </div>
              </div>
            </div>
        </div>
      </div>
      <!-- </el-col>
      <el-col :span="15"> -->
        <div>
          <div class="main-list">
              <div class="title">
                <el-form class="search-form" ref="searchForm" :inline="true">
                  <el-form-item class="form-item" label="" prop="keyword">
                    <el-input  prefix-icon="el-icon-full-screen"  v-model="queryParams2.storeName" class="input-item" placeholder="请输入商品关键字：商品名称" clearable maxlength="100" />
                  </el-form-item>
                  <el-form-item>
                    <el-button class="search-goods" type="danger" @click="doQueryGoods()"><Icon icon="ep:search" class="mr-5px" />查询商品</el-button>
                  </el-form-item>
                </el-form>
                <el-tabs class="tab-box" v-model="activeName" type="card"  @tab-click="switchTab">
                  <el-tab-pane label="全部" :name="0" />
                  <el-tab-pane :label="item.name" :name="item.id" :key="idx" v-for="(item,idx) in cateList" />
                </el-tabs>
              </div>
              <div class="goods-list">

                <div class="goods-item" :key="idx" v-for="(item,idx) in productList">
                    <div class="item" @click="clickGoods(item.id)"  >
                      <img class="image" lazy :src="item.image" />
                      <div class="goods-name">{{item.storeName}}</div>
                      <div class="goods-price">￥{{item.price}}</div>
                    </div>
                </div>

                <el-dialog title="选择商品规格"  v-model="dialogVisible" class="common-dialog" append-to-body>
                  <div class="goods-info">
                    <div class="name">{{productInfo.storeName}}</div>
                    <div class="price">￥{{productInfo.price}}</div>
                    <div class="num"><el-input-number class="input" v-model="goodsNum" :min="1" :max="1000"/></div>
                    <div class="spec-list">
                        <div class="spec-item" v-for="(attr,index) in productInfo.productAttr" :key="index">
                            <div class="spec-name">{{attr.attrName}}</div>
                            <div class="values">
                              <span  class="value" :class="{'active': value == newValue[index]}" v-for="(value,key) in attr.attrValueArr" :key="key" @click="changePropertyDefault(index, key,false)">{{value}}</span>
                            </div>
                        </div>
                    </div>
                  </div>
                  <template #footer>
                    <div  class="dialog-footer">
                      <el-button type="primary" class="main-button" @click="addToCart()">加入结算</el-button>
                      <el-button @click="closeGoodsDialog()">取 消</el-button>
                    </div>
                  </template>
                </el-dialog>
                <el-empty v-if="productList.length == 0" description="暂无商品..." />
              </div>
              <div>
                  <Pagination
                    :total="total"
                    v-model:page="queryParams2.pageNo"
                    v-model:limit="queryParams2.pageSize"
                    @pagination="getProductList"
                  />
              </div>
          </div>
        </div>
      <!-- </el-col>
    </el-row> -->
    </div>
  </ContentWrap>

  <settlement ref="settlementRef" :cart-data="cartList" :shop-id="shopId" @get-cart-list="getCartList" />
  <!-- <payResult ref="payResultRef" />
  <scanPay ref="scanPayRef" /> -->
  <hangList ref="hangListRef" @get-cart-list="getCartList" />

</template>

<script setup lang="ts" name="Cashier">
import * as ProductCategoryApi from '@/api/mall/product/category'
import * as StoreProductApi from '@/api/mall/product/product'
import * as ShopApi from '@/api/mall/store/shop'
import * as CashierApi from '@/api/mall/cashier'
import type { TabsPaneContext } from 'element-plus'
import { formatPast,formatDate } from '@/utils/formatTime'
import settlement from './settlement.vue'
// import payResult from './payResult.vue'
// import scanPay from './scanPay.vue'
import hangList from './hangList.vue'
import { useUserStore } from '@/store/modules/user'

const userStore = useUserStore()
const message = useMessage() // 消息弹窗
const shopId = ref(0)

const dialogVisible = ref(false)
const loading = ref(true) // 列表的加载中
const total = ref(1) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  name: undefined,
  shopId: undefined
})
const queryParams2 = reactive({
  pageNo: 1,
  pageSize: 8,
  storeName: null,
  cateId: null,
  isShow: 1,
  shopId: undefined
})
const queryFormRef = ref() // 搜索的表单

const activeName = ref(0)
const shopList = ref([])
const cateList = ref([])
const productList = ref([])
const memberInfo = ref({})
const productInfo = ref({})
const goodsNum = ref(1)
const newValue = ref([])
const thisProductSku = ref({})
const cartList =  ref([])

const getCartGoodsNumber = computed(() => { //计算购物车总数
	return cartList.value.reduce((acc, cur) => acc + cur.cartNum, 0)
})

const getCartGoodsPrice = computed(() =>{ //计算购物车总价
	let price = cartList.value.reduce((acc, cur) => acc + cur.cartNum * cur.price, 0);
	return parseFloat(price).toFixed(2);
})

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab.paneName, event)
}

const getShopList = async () => {
  try {
    const data = await ShopApi.getShopList()
    shopList.value = data
    if(userStore.getUser.shopId > 0){
      shopId.value = userStore.getUser.shopId
    }else{
      shopId.value = shopList.value[0].id
    }
    if(shopId.value == 0){
      message.error('请添加门店或者选择门店')
      return
    }
    queryParams.shopId = shopId.value 
    queryParams2.shopId = shopId.value 
    console.log('shopId:',shopId.value)

    getCateList()

    getProductList()

    getCartList(shopId.value)

  } finally {
    
  }
}
const getCateList = async () => {
  try {
    const data = await ProductCategoryApi.getCategoryList(queryParams)
    cateList.value = data

  } finally {
    
  }
}
const getProductList = async () => {
  try {
    const data = await StoreProductApi.getStoreProductPage(queryParams2)
    productList.value = data.list
    total.value = data.total

  } finally {
    
  }
}

const switchTab = (tab: TabsPaneContext, event: Event) => {
  console.log(tab.paneName)
  if(tab.paneName > 0){
    queryParams2.cateId = tab.paneName
    getProductList()
  }else{
    queryParams2.cateId = null
    getProductList()
  }
  
}

const doQueryGoods = () => {
  getProductList()
}

const clickGoods = async(id) => {
  dialogVisible.value = true
  const data = await CashierApi.getProductInfo({id:id})
  productInfo.value = data
  newValue.value = []
}


const changePropertyDefault = (index, key, isDefault) => { //改变默认属性值
	let valueStr = ''
	
	if(isDefault){
		newValue.value = []
		for(let i = 0;i < productInfo.value.productAttr.length;i++){
			newValue.value[i] = productInfo.value.productAttr[i].attrValueArr[0]
		}

	}else{
		newValue.value[index] = productInfo.value.productAttr[index].attrValueArr[key]
		//valueStr = newValue.value.join(',')
	}
	valueStr = newValue.value.join(',')
  console.log('newValue:',newValue.value)
	
	let productValue = productInfo.value.productValue[valueStr]
	console.log('productValue:',productValue)
	if(!productValue) {
		let skukey = JSON.parse(JSON.stringify(newValue.value))
		skukey.sort((a, b) => a.localeCompare(b))
		//console.log('skukey:',skukey)
		valueStr = skukey.join(',')
		productValue = productInfo.value.productValue[valueStr]
	}

  console.log('valueStr:',valueStr)
  console.log('productValue:',productValue)
  if(productValue){
    thisProductSku.value = productValue
	  productInfo.value.price = parseFloat(productValue.price).toFixed(2);
  }


}

const closeGoodsDialog = () => {
  dialogVisible.value = false
}

const addToCart = async() => {
    if(Object.keys(thisProductSku.value).length == 0) {
      message.error('请选择规格！')
      return
    }
    console.log('user:',thisProductSku.value)
    //let uid = memberInfo.value.id ? memberInfo.value.id : 0
    if(shopId.value == 0){
      message.error('请选择门店！')
      return
    }
    let data = {uid:0,shopId:shopId.value,productId:thisProductSku.value.productId,
                productAttrUnique:thisProductSku.value.unique,
                cartNum:goodsNum.value}

    const res = await CashierApi.addCart(data)

    getCartList(shopId.value)
    thisProductSku.value = {}
    closeGoodsDialog()
    
}

const getCartList = async(id) => {
  const res = await CashierApi.getCarts({shopId:id})
  cartList.value = res
}

const changeBuyNum = async(cart) => {
  console.log('cart:',cart)
  if(cart.cartNum < 1){
      message.error('数量不能小于1哦')
      return
  }
  await CashierApi.updateCartNum(cart)
}

const removeFromCart = async(id) => {
  await CashierApi.delCart({id:id})
  getCartList(shopId.value)
}

const hangUp = async() => {
  let ids = cartList.value.map(item => item.id);
  console.log('ids:',ids)
  if(ids.length == 0){
    message.error('暂无商品挂单')
    return
  }
  //console.log('ids:',ids.toString())
  await CashierApi.hangUp({ids:ids.toString()})
  getCartList(shopId.value)
}

const hangListRef = ref()
const hangOff = () => {
  hangListRef.value.open(shopId.value)
}

const settlementRef = ref()
// const payResultRef = ref()
// const scanPayRef = ref()
const doSettlement = () => {
  if(cartList.value.length == 0){
      message.error('请先加入商品！')
      return
  }
 settlementRef.value.open()
 //payResultRef.value.open()
 //scanPayRef.value.open()
}


/** 初始化 **/
onMounted(() => {
  getShopList()
})
</script>

<style lang="scss" scoped  >

.cart-container {
    width: 310px;
    min-height:560px;
    background: #FFFFFF;
    display: block;
    position: relative;
    // overflow-x: hidden;
    //     overflow-y: auto;
    left: 0px;
    top: 0px;
    border: #cccccc solid 1px;
    .title {
      height: 40px;
      width: 310px;
      background: #6c757d;
      border-bottom: #CCCCCC 2px solid;
      color: #FFFFFF;
      padding-top: 16px;
      padding-left: 1px;
      display: block;
      position: absolute;
      z-index: 999;
      clear: both;
      .logo {
        float: left;
        margin-left: 5px;
      }
      .member-info {
        float: left;
        .name {
          margin-left: 2px;
          margin-right: 3px;
        }
        .none {
            margin-left: 2px;
            margin-right: 5px;
            font-size: 13px;
        }
        .switch {
          padding: 8px 8px 8px 4px;
        }
      }
    }
    .carts {
      position:absolute;
      width:310px;
      height: 100%;
      overflow-x: hidden;
      overflow-y: auto;
      display: block;
      top:70px;
      bottom:0px;
     
      color: #666666;
      padding: 0px;
      .tab {
        // width: 50%;
        .cart-list {
            margin-bottom: 60px;
          .cart-item {
            border-bottom: dashed 1px #cccccc;
            height: 110px;
           // width: 310px;
            padding-top: 5px;
            .image {
                width: 50px;
                height: 50px;
                margin-left: 5px;
                border-radius: 5px;
                border: solid 1px #ccc;
                float: left;
                margin-top: 20px;
            }
            .info {
                float: left;
                padding-left: 5px;
                margin-top: 5px;
                .name {
                  font-weight: bold;
                  font-size: 12px;
                  width: 160px;
                  max-height: 30px;
                  overflow: hidden;
                  display: -webkit-box;
                  -webkit-box-orient: vertical;
                  -webkit-line-clamp: 2;
                }
                .spec {
                  font-size: 12px;
                  width: 160px;
                  height: 20px;
                  margin-top: 2px;
                  .item {
                    margin-right: 2px;
                    border-radius: 5px;
                    text-align: center;
                    height: 20px;
                    line-height: 20px;
                    float: left;
                    display: block;
                    color: #606266;
                    cursor: pointer;
                    background: #cceeee;
                    padding: 0px 3px 0px 3px;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                  }
                }
                .input {
                  width: 120px;
                  margin-top: 2px;
                }
            }
            .option {
                margin-top: 5px;
                float: right;
                text-align: right;
                margin-right: 10px;
                .remove {
                  font-size: 12px;
                  cursor: pointer;
                }
                .total {
                  margin-top: 25px;
                  font-size: 16px;
                  color: #ff5b57;
                }
            }
          }
        }
        .empty {
          margin-top: 200px;
          width: 310px;
        }
      }
    }
    .footer {
      position: absolute;
      z-index: 999;
      background: #6c757d;
      bottom: -120px;
      height: 120px;
      left:-2px;
      padding-top: 5px;
      padding-right: 10px;
      color: #FFFFFF;
      display: block;
      border: solid 3px #cccccc;
      .number {
        float: right;
        margin: 5px;
        font-size: 13px;
        .total-price {
            margin-top: 3px;
            .num {
              color: #ff5b57;
              font-size: 20px;
            }
        }
      }
      .options {
          text-align: center;
          cursor: pointer;
          float: left;
          color: #FFFFFF;
          margin:0 auto;
      }
    }
  }




.main-list {
    min-height: 700px;
    width: 100%;
    min-width: 760px;
    margin-left: 20px;
    margin-right: 2px;
    overflow: auto;
    display: block;
    background: #FFFFFF;
    margin-bottom: 10px;
    .title {
      height: 106px;
      min-width: 700px;
      background: #ffffff;
      padding: 5px;
      color: red;
      top: 0px;
      .search-form {
        height: 50px;
        .form-item {
          margin-right: -2px;
        }
        .input-item {
          min-width: 456px;
          height: 50px;

        }
        .search-goods {
          height: 50px;
          margin-left: 3px;
        }
      }
      .tab-box {
        margin-top: 8px;
        width: 100%;
      }
    }
    .goods-list {
      height: 100%;
      width: 100%;
      margin-left: 2px;
      margin-bottom: 20px;
      .goods-item {
        width: 23%;
        min-height: 300px;
        padding: 3px;
        float: left;
        background: #ffffff;
        text-align: left;
        cursor: pointer;
        .item {
          background: #ffffff;
          padding: 5px;
          border-radius: 5px;
          border: solid 1px #cccccc;
          margin: 0px;
          .goods-name {
            margin-top: 10px;
            font-size: 18px;
            color: #666666;
            height: 30px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
          .goods-price {
            color: #ff5b57;
            font-size: 18px;
            font-weight: bold;
          }
          .image {
            width: 100%;
            height: 220px;
            border-radius: 3px;
          }
        }
      }
    }
  }

  @media (min-width: 768px) {
  .container {
    max-width: 750px;
  }
}

.goods-info {
  border: solid 1px #ccc;
  padding: 30px;
  border-radius: 5px;
  .name {
    height: 40px;
    font-weight: bold;
    font-size: 20px;
  }
  .price {
    height: 40px;
    color: #ff5b57;
    font-size: 16px;
  }
  .spec-list {
    border: solid 1px #ccc;
    padding: 20px;
    margin-top: 10px;
    border-radius: 6px;
    .spec-item {
        margin-bottom: 20px;
      .spec-name {
          font-weight: bold;
          font-size: 16px;
      }
      .values {
          display: block;
          padding-top: 10px;
          margin-left: 0px;
          padding-left: 0px;
          font-size: 12px;
          .value {
            border: solid 1px #cceeee;
            margin-right: 10px;
            padding: 8px 15px 5px 15px;
            cursor: pointer;
            border-radius: 4px;
            background: rgba(0, 172, 172, 0.1);
            color: #666666;
          }
          .active {
            border: solid 1px #ff5891;
            background: #ff5b57;
            color: #FFFFFF;
          }
      }
    }
  }
}


</style>